package com.yxb.thirdsdk.push;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.audience.AudienceType;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.push.model.notification.PlatformNotification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class JpushService {

    private static final Logger LOGGER  = LoggerFactory.getLogger(JpushService.class);

    @Resource(name = "jpushClient")
    private JPushClient  jPushClient;


    public JpushService() {
    }

    public JpushService(JPushClient jPushClient) {
        this.jPushClient = jPushClient;
    }

    public void sendMsg(String userId,String alert)  {

        AudienceTarget  audienceTarget  = AudienceTarget.newBuilder().addAudienceTargetValue(userId).setAudienceType(AudienceType.ALIAS).build();
        Audience audience  = Audience.newBuilder().addAudienceTarget(audienceTarget).build();
        IosNotification iosNotification  = IosNotification.newBuilder().setAlert(alert).build();
        Notification  notification  = Notification.newBuilder().addPlatformNotification(iosNotification).build();
        Options options = Options.newBuilder().setApnsProduction(true).build();
        PushPayload pushPayload = PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(audience).setNotification(notification).setOptions(options).build();
        PushResult pushResult = null;
        try {
            pushResult = jPushClient.getPushClient().sendPush(pushPayload);
        } catch (APIConnectionException e) {
            LOGGER.info("发送push异常:", e);
        } catch (APIRequestException e) {
            LOGGER.info("发送push异常:", e);
        }

        if ( pushResult.isResultOK()) {
            System.out.println(pushResult.toString());
        }


    }






}
